package com.zam.exception;

import com.zam.comment.Result;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;

import static com.zam.comment.Constants.CODE_401;

/**
 * @Author 
 * @Date 2023/5/25 11:12
 * @Description: 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandlerResolver {
    private final static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandlerResolver.class);
 
 
 /**
     * 文件上传超过最大限制异常
     *
     * @return R
     */
    @ExceptionHandler(value = MultipartException.class)
    @ResponseBody
    public Result handleBusinessException(MaxUploadSizeExceededException ex) {
        String msg;
        if (ex.getCause().getCause() instanceof FileSizeLimitExceededException) {
            LOGGER.error("[单文件大小不得超过100M]");
            msg = "单文件大小不得超过100M";
        } else if (ex.getCause().getCause() instanceof SizeLimitExceededException) {
            LOGGER.error("[总上传文件大小不得超过200M]");
            msg = "总上传文件大小不得超过200M";

        } else {
            LOGGER.error("请检查文件类型及大小是否符合规范");
            msg = "请检查文件类型及大小是否符合规范";
        }
        return Result.error(CODE_401, msg);
 
    }
}